<template>
  <div class="flex-1">
    <div v-if="isLogin">
      <n-button style="height: 100px" @click="handleLogin" block quaternary> 请先
        <div class="text-blue-500">登录</div>
        再回复哦~
      </n-button>
    </div>
    <div v-else class="space-y-3">
      <n-input ref="inputRef" v-model:value="content" type="textarea"></n-input>
      <div  class="flex justify-end">
        <n-button type="success" class="bg-green-600" @click.stop="handleReply">回复</n-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">


import {ref} from "vue";
import { useUserStore} from "@/store/module/user";
import {useAppStore} from "@/store/module/app";
import {storeToRefs} from "pinia";
import api from "@/api";
import {useDebounceFn} from '@vueuse/core'

const userStore = useUserStore()
const {userInfo,isLogin} = storeToRefs(userStore)
const appStore = useAppStore()
const {authModalShow} = storeToRefs(appStore)

const inputRef = ref()
const content = ref('')

const props = defineProps({
  commentId: {
    type: Number,
    required: true
  },
  toId: {
    type: Number,
    required: true
  },
  toUsername: {
    type: String,
    required: true
  },
  toAvatar: {
    type: String,
    required: true
  },
  toContent: {
    type: String,
    required: true
  }
})

const emits = defineEmits(['replySuccess'])



const handleLogin = () => {
  authModalShow.value = true
}

const handleReply = useDebounceFn(() => {
  api.comment.createPostReply({
    commentId: props.commentId,
    fromId: userInfo.value.id,
    fromUsername: userInfo.value.username,
    fromAvatar: userInfo.value.avatar,
    fromContent: content.value,
    toId: props.toId,
    toUsername: props.toUsername,
    toAvatar: props.toAvatar,
    toContent: props.toContent,
  }).then(res => {
    if (res.data.code === 0) {
      emits('replySuccess',{
        commentId: props.commentId,
        fromId: userInfo.value.id,
        fromUsername: userInfo.value.username,
        fromAvatar: userInfo.value.avatar,
        fromContent: content.value,
        toId: props.toId,
        toUsername: props.toUsername,
        toAvatar: props.toAvatar,
        toContent: props.toContent,
      })
      content.value = ''
      window.$message.success('回复成功')
    }
  })
}, 200)


const doInputFocus = () => {
  inputRef.value.focus()
}

defineExpose({
  doInputFocus
})


</script>

<style scoped>

</style>